import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Layout from '../views/Layout.vue'
import Users from '../views/Users.vue'
import Roles from '../views/Roles.vue'
import Menus from '../views/Menus.vue'
import Admins from '../views/Admins.vue'
import Dashboard from '../views/Dashboard.vue'
import { ensureDynamicRoutes } from './dynamic'

const routes = [
  { path: '/login', component: Login, meta: { title: 'Login', icon: 'User' } },
  {
    path: '/',
    component: Layout,
    meta: { title: 'breadcrumb.home', icon: 'House' },
    children: [
      { path: '', redirect: '/dashboard' },
      { path: 'dashboard', component: Dashboard, meta: { title: 'breadcrumb.dashboard', icon: 'House' } },
      { path: 'users', component: Users, meta: { title: 'breadcrumb.users', icon: 'User' } },
      { path: 'system/roles', component: Roles, meta: { title: 'breadcrumb.roles', icon: 'UserFilled' } },
      { path: 'system/menus', component: Menus, meta: { title: 'breadcrumb.menus', icon: 'Menu' } },
      { path: 'system/admins', component: Admins, meta: { title: 'breadcrumb.admins', icon: 'Avatar' } }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  try {
    const token = localStorage.getItem('token')
    if (!token && to.path !== '/login') return next('/login')
    if (token && to.path === '/login') return next('/')
    // build dynamic routes after login
    if (token && to.path !== '/login') {
      await ensureDynamicRoutes()
    }
    next()
  } catch (error) {
    console.error('Router navigation error:', error)
    // 如果动态路由加载失败，仍然允许导航到静态路由
    next()
  }
})

export default router


